package com.dabai.dbutils.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;

import com.dabai.dbutils.R;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;


/**
 * 本地随机验证码 弹窗工具类
 * @author 故事与猫
 */
public class VerificationCodeDialog {


    private static String realCode;

    public interface OnVerification {
        /**
         * 输入正确
         */
        void correct();
        /**
         * 输入错误
         */
        void error();
        /**
         * 取消输入
         */
        void cancel();
    }


    /**
     * 展示一个 简单 4位数字 验证码弹窗,返回一个 Dialog对象
     */
    public static Dialog showSimpleVerificationDialog(Context context, OnVerification onVerification) {

        View dialogView = View.inflate(context, R.layout.dialog_verification_code, null);
        TextInputLayout til1 = dialogView.findViewById(R.id.til1);
        ImageView imageView = dialogView.findViewById(R.id.VerificationCodeImage);

        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setLineNumber(0);

        imageView.setImageBitmap(verificationCode.createBitmap());
        realCode = verificationCode.getCode();

        imageView.setOnClickListener(v -> {
            imageView.setImageBitmap(verificationCode.createBitmap());
            realCode = verificationCode.getCode();
        });

       return new MaterialAlertDialogBuilder(context)
                .setTitle("验证码识别")
                .setView(dialogView)
                .setPositiveButton("确认", (dialog, which) -> {
                    String etCode = til1.getEditText().getText().toString().toLowerCase();
                    if (etCode.equals(realCode)) {
                        onVerification.correct();
                    } else {
                        onVerification.error();
                    }
                })
                .setNeutralButton("取消", (dialog, which) -> {
                    onVerification.cancel();
                })
                .show();
    }

}
